package com.tianqu.tms.www.transfer.controller;

import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn000436Bo;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn000603Bo;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dao.TransferProcessHistoryDaoImp;
import com.tianqu.tms.dto.TransferProcessHistoryDto;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.www.transfer.actionform.PublicSecurityAuditActionForm;

public class PublicSecurityAuditResultController extends TmsController {
	private Logger logger = Logger.getLogger(PublicSecurityAuditResultController.class);

	@SuppressWarnings("unchecked")
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = getTxController();
		try {
			controller.begin();
			TransferAcceptedInfo acceptedInfo = TransferAcceptedInfo.getInstance();
			
			PublicSecurityAuditActionForm inputForm = (PublicSecurityAuditActionForm)uc.getInputForm();
			int transferType = inputForm.getTransferType();
			boolean auditResult = true;
			boolean auditResult2 = true;
			boolean auditResult3 = true;
			String reason = "";
			
			acceptedInfo.setSerial(inputForm.getSerial());
			acceptedInfo.setVin(inputForm.getVin());
			acceptedInfo.setLicensePlate(inputForm.getLicensePlate());
			
			if (transferType == 3) {
				acceptedInfo.setEpStandard(inputForm.getEpStandard()); // 环保达标
				if (inputForm.getEpStandard() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					reason = "环保达标：未达标";					
				}
			}
			
			if (transferType == 2 || transferType == 3 || transferType == 5) {
				acceptedInfo.setCarReplaceType(inputForm.getCarReplaceType()); // 客车换型
				if (inputForm.getCarReplaceType() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "客车换型：是";	
				}
			}
			
			if (transferType == 2 || transferType == 3 || transferType == 5|| transferType == 6) {
				acceptedInfo.setCarPeccancy(inputForm.getCarPeccancy()); // 车辆违章
				acceptedInfo.setOverdue(inputForm.getOverdue()); // 超检审核
				acceptedInfo.setMortgage(inputForm.getMortgage()); // 抵押审核
				acceptedInfo.setSealup(inputForm.getSealup()); // 查封审核
				
				if (inputForm.getCarPeccancy() != 1) {
					auditResult = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "车辆违章：有违章未处理";	
				}
				
				if (inputForm.getOverdue() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "超检审核：车辆检验逾期";	
				}
				
				if (inputForm.getMortgage() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "抵押审核：已抵押";	
				}
				
				if (inputForm.getSealup() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "查封审核：查封";	
				}
			}
			
			if (transferType == 2 || transferType == 3 || transferType == 5|| transferType == 7) {
				acceptedInfo.setDrivingLicense(inputForm.getDrivingLicense()); // 行驶证
				
				if (inputForm.getDrivingLicense() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "行驶证编号：不符";	
				}
			}
			
			if (transferType == 2 || transferType == 3 || transferType == 5|| transferType == 6|| transferType == 7) {
				acceptedInfo.setRegistration(inputForm.getRegistration()); // 登记证书
				acceptedInfo.setScrapOverdue(inputForm.getScrapOverdue()); // 报废超期
				acceptedInfo.setRobbery(inputForm.getRobbery()); // 盗抢审核
				acceptedInfo.setOwnerEscaping(inputForm.getOwnerEscaping()); // 原车主在逃
				acceptedInfo.setOwnerScrap(inputForm.getOwnerScrap()); // 原车主报废车
				
				if (inputForm.getRegistration() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "登记证书编号：不符";	
				}


				if (inputForm.getScrapOverdue() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "报废超期：超期";	
				}
				
				if (inputForm.getRobbery() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "盗抢审核：有";	
				}

				if (inputForm.getOwnerEscaping() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "原车主信息在逃审核：在逃";	
				}

				if (inputForm.getOwnerScrap() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "原车主信息报废车审核：强制报废";	
				}
			}

			acceptedInfo.setNewEscaping(inputForm.getNewEscaping()); //	新车主在逃
			if (inputForm.getNewEscaping() != 1) {
				auditResult = false;
				auditResult2 = false;
				auditResult3 = false;
				if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
				reason = reason + "新车主信息在逃审核：在逃";	
			}
			
			if (transferType == 1 || transferType == 2 || transferType == 3 || transferType == 5|| transferType == 6|| transferType == 7) {
				acceptedInfo.setNewScrap(inputForm.getNewScrap()); // 新车主报废车
				if (inputForm.getNewScrap() != 1) {
					auditResult = false;
					auditResult2 = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "新车主信息报废车审核：强制报废";	
				}
			}
			
			if (transferType == 1 || transferType == 2 || transferType == 4 || transferType == 5) {
				acceptedInfo.setNewLive(inputForm.getNewLive()); //	新车主居住证
				if (inputForm.getNewLive() != 1) {
					auditResult = false;
					auditResult3 = false;
					if (!StringUtil.isNullOrBlank(reason)) reason = reason + "，";
					reason = reason + "新车主信息居住证审核：未通过";	
				}
			}
			
			// 审核结果的判断：
			// # 根据业务类型，当页面所有填写的内容项，全为默认值，即为1时，公安审核状态为“1：审核通过”	
			acceptedInfo.setTransferRegister(2);
			if (auditResult == true) {
				acceptedInfo.setTransferRegister(1);
			}
//			# 根据业务类型，当页面所有填写的内容项，除“车辆违章（carPeccancy）”外全为默认值，即为1时，公安审核状态为“5：有违章”												
			else if (auditResult3 == true  && inputForm.getCarPeccancy() != 1) {
				acceptedInfo.setTransferRegister(5);
			}
			// # 根据业务类型，当页面填写的“新车主居住证（newLive）”为“2：无居住证明”时，公安审核状态为“4：审核中”
			else if (auditResult == false && auditResult2 == true) {
				acceptedInfo.setTransferRegister(4);
			}
			// # 根据业务类型，当页面所有填写的内容项，除“车辆违章（carPeccancy）”和“新车主居住证（newLive）”外，至少有一条不为默认值，即至少有一条不为1时，公安审核状态为“3：审核未通过”
			else if (auditResult2 == false) {
				acceptedInfo.setTransferRegister(3);
			}
			
			// 更新 过户业务基本信息表 (tms_transfer_accepted_info)
			TmsUserProfile profile = uc.getUserProfile();
			acceptedInfo.setUpdateUserId(profile.getUniqueId());// 存入更新者Id
			if (inputForm.getStatus() == 1) {
				acceptedInfo.setStatus(2);
			} else {
				acceptedInfo.setStatus(inputForm.getStatus());
			}
			acceptedInfo.updatePublicSecurityAuditBySerial(acceptedInfo);
			
			// 插入 过户流程操作记录表（tms_transfer_process_history）
			TransferProcessHistoryDto transferProcessHistoryDto = new TransferProcessHistoryDto();
			transferProcessHistoryDto.setBusinessType(47);
			transferProcessHistoryDto.setInsertUserId(profile.getUniqueId());
			transferProcessHistoryDto.setSerial(inputForm.getSerial());
			transferProcessHistoryDto.setReason(inputForm.getReason());
			TransferProcessHistoryDaoImp transferProcessHistoryDao = (TransferProcessHistoryDaoImp) TransferProcessHistoryDaoImp.getInstance(TmsDao.TMS_TRANSFER_PROCESS_HISTORY);
			transferProcessHistoryDao.insertHisInfoBySerial(transferProcessHistoryDto);
			
			// 插入 公安审核信息表（tms_transfer_Register_info）
			acceptedInfo.insertTransferRegisterInfo(acceptedInfo);
			
			// 通过API接口将录入信息传送给微信平台，具体请参照微信平台同步接口（接口编号：601），进行推送，推送内容如下：
//			  # 审核结果同步到手机，并发送推送，如果审核通过，推送审核通过；如果审核未通过，推送未通过的内容项。		
//			  审核通过：【公安审核通过通知】：您好！您申请办理的流水号{过户流水号（serial）}车牌号{车牌号码（licensePlate）}（如果是新车/外地转入车，则为“车架号后六位{vin码（vin）后六位}”），		
//			                                                             经公安网审核通过，可以继续办理业务。		
//			  审核未通过：【公安审核未通过通知】：您好！您申请办理的流水号{过户流水号（serial）}车牌号{车牌号码（licensePlate）}（如果是新车/外地转入车，则为“车架号后六位{vin码（vin）后六位}”），		
//			                                                             经公安网审核未通过，原因为：{原因}。		
//			  审核中：【公安审核通知】：您好！您申请办理的流水号{过户流水号（serial）}车牌号{车牌号码（licensePlate）}（如果是新车/外地转入车，则为“车架号后六位{vin码（vin）后六位}”），		
//			                                                             经公安网审核｛车辆违章（carPeccancy）｝｛新车主居住证（newLive）｝未通过，请您及时处理，以便继续办理业务。		
//			有违章：【公安审核通过通知】：您好！您申请办理的流水号{过户流水号（serial）}车牌号{车牌号码（licensePlate）}（如果是新车/外地转入车，则为“车架号后六位{vin码（vin）后六位}”），													
//								经公安网审核您有违章未处理，请及时处理。）													

			String pushContent = "";
			if (transferType == 1 || transferType == 4) {
				// 新车/外地转入车
				pushContent = "【公安审核通过通知】：您好！您申请办理的流水号" + acceptedInfo.getSerial() + "车架号后六位" + acceptedInfo.getVin();
				
			} else{
				// 本地过户，本地转出，县区转入
				pushContent = "【公安审核通过通知】：您好！您申请办理的流水号" + acceptedInfo.getSerial() + "车牌号" + acceptedInfo.getLicensePlate();
			}
			
			if (acceptedInfo.getTransferRegister() == 1) {
				// 1：公安审核通过
				pushContent = pushContent + "经公安网审核通过，可以继续办理业务。";
			} 
			
			if (acceptedInfo.getTransferRegister() == 5) {
				// 5：有违章
				pushContent = pushContent + "经公安网审核您有违章未处理，请及时处理。";
			} 
			
			if (acceptedInfo.getTransferRegister() == 3) {
				// 3：公安审核未通过
				pushContent = pushContent + "经公安网审核未通过，原因为：" + reason + "。";
			}
			
			if (acceptedInfo.getTransferRegister() == 4) {
				// 4：公安审核中
				pushContent = pushContent + "经公安网审核" + reason + "未通过，请您及时处理，以便继续办理业务。";
			}

			//接口编号：603；【TMS_web】=》微信终端
			TransferDataSyn000603Bo transferDataSyn000603Bo = new TransferDataSyn000603Bo();
			if (!StringUtil.isNullOrBlank(inputForm.getAttnId())){
				transferDataSyn000603Bo.setAttnId(inputForm.getAttnId());
				transferDataSyn000603Bo.setPushContent(pushContent);
				MobileMessage msg = new MobileMessage();
				msg.putValue("safe", "0");
				transferDataSyn000603Bo.setMobileMessage(msg);
				WeChatMqApi.getInstance().call(transferDataSyn000603Bo);
			}
			
			// 提取下一个待处理的流水号信息，如果没有下一个流水号，返回到公安审核列表页。
			// 到系统功能配置表（tms_configure）获取参数名为gashGroup的值,确定分组
			String strGashGroup = Registry.getConfig(TmsConstants.GASH_GROUP);
			String[] gashGroup = strGashGroup.split("\\]\\[");

			int group = -1;
			String next = "";
			if (gashGroup != null && gashGroup.length > 0) {
				for (int i = 0; i < gashGroup.length; i++) {
					if (gashGroup[i].indexOf(acceptedInfo.getSerial().substring(acceptedInfo.getSerial().length() - 1)) >= 0) {
						group = i;
					}
				}
				
				if (group > -1) {
					List<String> serialList = acceptedInfo.findListBySerial(gashGroup[group].replaceAll("\\[", "").replaceAll("\\]", "").split(","));
					
					if (null != serialList && serialList.size() > 0) {
						if (group == 0)  next = "A";
						if (group == 1)  next = "B";
						if (group == 2)  next = "C";
						uc.setAttribute("next", next);
					}
				}
			}
			
			controller.commit();
			//接口编号：436；【TMS_web】公安审核 =》【TMS_app】同步
			TransferDataSyn000436Bo transferDataSyn000436Bo = new TransferDataSyn000436Bo();
			transferDataSyn000436Bo.setMarketNo(TmsConstants.MARKET_NO);
			transferDataSyn000436Bo.setRemark(reason);
			transferDataSyn000436Bo.setSerial(inputForm.getSerial());
			//transferDataSyn000436Bo.setStatus(transferType);
			transferDataSyn000436Bo.setStatus(acceptedInfo.getTransferRegister());//modify by huangwei
			
			WeChatMqApi.getInstance().call(transferDataSyn000436Bo);
			
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");

	}
}
